package com.ruis.kotboot.common.util

import com.ruis.kotboot.common.core.RuisException
import com.ruis.kotboot.common.plug.Digests
import com.ruis.kotboot.common.plug.Encodes
import com.ruis.kotboot.common.plug.HttpUtils
import okhttp3.FormBody
import okhttp3.Request
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import java.util.*

object ruisUtil{
    private val logger = LoggerFactory.getLogger(this::class.java)

    fun md5(input: String): String {
        return Encodes.encodeHex(Digests.md5(input.toByteArray(charset("utf-8")))).toUpperCase()
    }
    fun sha1(input: String): String {
        return Encodes.encodeHex(Digests.sha1(input.toByteArray(charset("utf-8")))).toUpperCase()
    }

    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     *
     * @param cont
     * @return
     */
    fun escapeExprSpecialWord(cont: String): String {
        var content = cont
        if (StringUtils.isNotBlank(content)) {
            val fbsArr = arrayOf("\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|")
            for (key in fbsArr) {
                if (content.contains(key))
                    content = content.replace(key, "\\" + key)
            }
        }
        return content
    }

    /**
     * emoji表情替换
     *
     * @param source 原字符串
     * @param slipStr emoji表情替换成的字符串
     * @return 过滤后的字符串
     */
    fun filterEmoji(source: String, slipStr: String): String? {
        return if (StringUtils.isNotBlank(source)) {
            source.replace("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]".toRegex(), slipStr)
        } else {
            source
        }
    }


    fun getRealIpAddrs(): String? {
        val request=HttpUtil.getRequest()
        var ip: String? = request.getHeader("x-forwarded-for")
        if (StringUtils.isNotBlank(ip) && !"unknown".equals(ip, ignoreCase = true)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip!!.indexOf(",") != -1) {
                ip = ip.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
            }
        }
        if (StringUtils.isBlank(ip) || "unknown".equals(ip, ignoreCase = true))
            ip = request.getHeader("Proxy-Client-IP")
        if (StringUtils.isBlank(ip) || "unknown".equals(ip, ignoreCase = true))
            ip = request.getHeader("WL-Proxy-Client-IP")
        if (StringUtils.isBlank(ip) || "unknown".equals(ip, ignoreCase = true))
            ip = request.getHeader("HTTP_CLIENT_IP")
        if (StringUtils.isBlank(ip) || "unknown".equals(ip, ignoreCase = true))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR")
        if (StringUtils.isBlank(ip) || "unknown".equals(ip, ignoreCase = true))
            ip = request.getHeader("X-Real-IP")
        if (StringUtils.isBlank(ip) || "unknown".equals(ip, ignoreCase = true))
            ip = request.remoteAddr
        logger.debug("ruisUtil>getRealIpAddrs:获取客户端ip: $ip")
        return ip
    }

    private fun getValue(): Int {
        //假设这里就是你从数据库中读取的一组数字
        val values = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
        val r = Random().nextInt(10)
        //然后在经过你的方法，删除数据库中取得的指定的值，就是删除values[r]
        return values[r]
    }
    fun getQQYYCode(len: Int=0): String {
        var lens = len
        if (lens <= 0) lens = 6//默认6位
        val sb = StringBuilder()
        for (i in 0 until lens) {
            val value = getValue()
            if (i == 0 && value == 0)
                continue
            sb.append(value)
        }
        return sb.toString()
    }

    /**
     * 获取4位随机验证码
     * @return
     */
    fun getValidationCode(): String {
        return (Random().nextInt(8999) + 1000).toString()
    }

    /**
     * 获取6位随机验证码
     * @return
     */
    fun getValidationCode6w(): String {
        return (Random().nextInt(899999) + 100000).toString()
    }


    /**
     * 替换html
     *
     * @param cont
     * @return
     */
    fun clearHtmls(cont: String?,higlev:Boolean=true): String {
        var ret=cont?:return ""
        if(higlev) {
            ret = ret.replace(";", "；")
                    .replace("`", "｀")
                    .replace("\\", "＼")
        }
        return ret
                .replace("<","＜")
                .replace(">","＞")
                .replace("?","？")
                .replace("\"","＂")
                .replace("'","＇")
    }

    /**
     * 删除html
     *
     * @param cont
     * @return
     */
    fun rmHtmls(cont: String?): String {
        return cont?.replace("<?[^/?(br)|(p)][^><]*>","")?:""
    }


    /**
     * 发送鼎信科技验证码
     */
    fun sendValidationMsg(phone:String?, code:String?, ptlId:String?,appcode:String?):String{
        if(StringUtils.isBlank(phone))throw RuisException(2)
        if(StringUtils.isBlank(code))throw RuisException(2)
        if(StringUtils.isBlank(ptlId))throw RuisException(2)
        if(StringUtils.isBlank(appcode))throw RuisException(2)
        val fbody = FormBody.Builder()
        fbody.add("tpl_id", ptlId)
        fbody.add("mobile", phone)
        if (StringUtils.isNotBlank(code))
            fbody.add("param", "code:$code")
        val request = Request.Builder()
                .addHeader("Connection", "keep-alive")
                .addHeader("Authorization","APPCODE $appcode")
        val req=request.url("http://dingxin.market.alicloudapi.com/dx/sendSms").post(fbody.build()).build()
        val call = HttpUtils.getClient().newCall(req)
        val res = call.execute()
        return res.body().string()
    }
}